#pragma once

#include <pthread.h>
#include <queue>

const int defaultNum = 10;

template<class Type>
class BlockQueue
{

    bool _isFull() const
    {
        return _queue.size() >= _capacity;
    }

    bool _isEmpty() const
    {
        return _queue.size() <= 0;
    }

public:
    
    BlockQueue()
        :_capacity(defaultNum)
        ,_csleep_num(0)
        ,_psleep_num(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_full_cond, nullptr);
        pthread_cond_init(&_empty_cond, nullptr);
    }

    template<class T>
    void push(T&& data)
    {
        pthread_mutex_lock(&_mutex);

        while (_isFull())   // pthread_cond_wait 函数可能调用失败或者进入出去后的线程没抢到锁，需要 while 再次判断
        {
            ++_psleep_num;
            pthread_cond_wait(&_full_cond, &_mutex);
            --_psleep_num;
        }

        int datatemp = data++;
        _queue.emplace(datatemp);
        std::cout << " 生产了一个商品，编号: " << datatemp << std::endl;

        if (_csleep_num > 0)
        {
            pthread_cond_signal(&_empty_cond);
        }

        pthread_mutex_unlock(&_mutex);
    }

    Type pop()
    {
        pthread_mutex_lock(&_mutex);

        while (_isEmpty())
        {
            ++_csleep_num;
            pthread_cond_wait(&_empty_cond, &_mutex);
            --_csleep_num;
        }
        
        Type data = std::move(_queue.front());
        _queue.pop();
        std::cout << " 消费了一个商品，编号: " << data << std::endl;

        if (_psleep_num > 0)
        {
            pthread_cond_signal(&_full_cond);
        }

        pthread_mutex_unlock(&_mutex);

        return data;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_full_cond);
        pthread_cond_destroy(&_empty_cond);
    }

private:

    std::queue<Type> _queue;
    int _capacity;

    pthread_mutex_t _mutex;
    pthread_cond_t _full_cond;
    pthread_cond_t _empty_cond;

    int _csleep_num;
    int _psleep_num;
};
